package belf.migrate.core.util;

import belf.migrate.core.exception.HttpException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 基于JDK自带的API实现基本的HTTP GET/POST
 */
@Slf4j
public class JsonHttp {

    /**
     * GET方式请求一个url地址，返回响应的BODY
     *
     * @param url
     * @return
     */
    public String get(String url) throws HttpException {
        try {
            // 要访问的URL
            URL u = new URL(url);

            // 创建 HttpURLConnection 对象
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            // 设置请求方法为 POST
            conn.setRequestMethod("GET");
            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 读取响应
            int responseCode = conn.getResponseCode();
            log.debug("GET Response Code :: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_CREATED) { // HTTP 201 Created
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return response.toString();
                }
            } else {
                log.error("GET request not worked: {}", url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new HttpException("HTTP GET error", e);
        }

        return "";
    }

    public void postText(String url, String text) throws HttpException {
        HttpURLConnection conn = null;
        try {
            // 要访问的URL
            URL u = new URL(url);

            // 创建 HttpURLConnection 对象
            conn = (HttpURLConnection) u.openConnection();

            // 设置请求方法为 POST
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 允许写入内容
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.connect();

            // 写入请求体
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = text.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
                os.flush();
            }

            // 读取响应
            int responseCode = conn.getResponseCode();
            log.debug("POST Response Code :: " + responseCode);


        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpException("HTTP GET error", e);
        } finally {
            conn.disconnect();
        }

    }

    public String postJson(String url, String json) throws HttpException {
        try {
            // 要访问的URL
            URL u = new URL(url);

            // 创建 HttpURLConnection 对象
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            // 设置请求方法为 POST
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 允许写入内容
            conn.setDoOutput(true);

            // 写入请求体
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = conn.getResponseCode();
            log.debug("POST Response Code :: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_CREATED) { // HTTP 201 Created
                try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return response.toString();
                }
            } else {
                log.error("POST request not worked: {}", url);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpException("HTTP GET error", e);
        }

        return "";
    }
}
